import 'dart:developer';
import 'package:umeng_apm_sdk/umeng_apm_sdk.dart';
import 'package:get/get.dart';
import 'package:scrollview_observer/scrollview_observer.dart';
import 'package:ball_lion/entity/record/channel_entity.dart';
import 'package:ball_lion/server/api/record_api.dart';
import 'package:ball_lion/utils/user.dart';

class ChannelFilterLogic extends GetxController {
  int _channelType = Get.arguments ?? 0;
  bool _editable = false;
  final scrollController = ApmScrollController();
  final leftController = ApmScrollController();
  late final contentController =
      ListObserverController(controller: scrollController);

  List<ChannelEntity> myChannels = [];
  Map<int, ChannelEntity> _myChannelsMap = {};
  List<ChannelAreaEntity> areas = [];
  ChannelAreaEntity? _area;
  String _selectCountry = "";

  bool get editable => _editable;
  Map<int, ChannelEntity> get myChannelsMap => _myChannelsMap;
  String get selectCountry => _selectCountry;
  ChannelAreaEntity? get area => _area;
  int get channelType => _channelType;

  set channelType(int value) {
    _channelType = value;
    update();
  }

  set area(ChannelAreaEntity? value) {
    _area = value;
    update();
  }

  set selectCountry(String value) {
    _selectCountry = value;
    update();
  }

  set myChannelsMap(Map<int, ChannelEntity> value) {
    _myChannelsMap = value;
    update();
  }

  set editable(bool value) {
    _editable = value;
    update();
  }

  @override
  onReady() {
    requestMyChannels();
    requestChannelsAll();
  }

  void updateChannelsMap() => myChannelsMap = myChannels
      .asMap()
      .map((key, value) => MapEntry(value.channelId ?? 0, value));

  Future requestMyChannels() async {
    final channels = await RecordApi.myChannels(channelType);
    log("get my league channels ${channels?.map((e) => e.channelId)}");
    if (channels == null) {
      return;
    }
    myChannels = channels;
    updateChannelsMap();
    update();
  }

  Future requestChannelsAll() async {
    final areas = await RecordApi.channelsAll(channelType);
    if (areas == null) {
      return;
    }
    this.areas = areas;
    area = areas
        .firstWhereOrNull((element) => element.area == (area?.area ?? "欧洲"));
    if (area == null && areas.isNotEmpty) {
      area = areas.first;
    }
    if (area != null &&
        (area?.list?.isNotEmpty ?? false) &&
        selectCountry.isEmpty) {
      selectCountry = area?.list?.first.country ?? "";
    }
    update();
  }

  Future updateMyChannels() async {
    User.needLogin(() async {
      final r = await RecordApi.updateChannel(myChannels, channelType);
      log("update league channels $r");
      if (!r) {
        await RecordApi.updateChannel(myChannels, channelType);
      }
    });
  }

  Future clickEdit() async {
    if (User.isLogin) {
      editable = !editable;
      if (!editable) {
        updateMyChannels();
      }
    } else {
      await User.needLogin(() => null);
      requestMyChannels();
    }
  }
}
